import {message} from 'antd';
import {history} from '@umijs/max';
import request from '@/utils/request';


const getStatus = (status: string) => {
  switch (status) {
    case '0':
      return '离线';
    case '1':
      return '空闲中';
    case '2':
      return '已插枪';
    case '3':
      return '充电中';
    case '4':
      return '故障';
    default:
      return ''
  }
}
const monitorModel = {
  namespace: 'monitor',
  state: {
    pileList: [],
    pileCode: '',
    stationId: '',
    total: 0,
    pageNum: 1,
    pageSize: 10
  },
  effects: {
    *init(_, {call, put}){
      // const data2 = yield call(() => request('/api2/games/getGames'));
      yield put({
        type: 'setState',
        payload: {
          pileCode: '',
          stationId: undefined,
        }
      })
      yield put({
        type: 'load',
        payload: {
          pageNum: 1,
          pageSize: 10
        }
      })
    },
    *load({payload}, {call, put, select}){
      // const A =
      const {pileCode, stationId} = yield select(({monitor}) => monitor);
      const {code, data: {records: data = [], total = 0} = {}} = yield call(() =>
          request('/api1/monitorDevice/pileAndGunInfoWithPage', {method: 'get', params: {...payload, pileCode, stationId}}));
      console.log('pileCode', pileCode);
      if (code && code === 200){
        const temArr = [];
        console.log('原始数据', data);
        const pileObjArr: any = {}
        data.forEach((e: any) => {
          if (!pileObjArr[e.pileCode] || !pileObjArr[e.pileCode].length){
            pileObjArr[e.pileCode] = data.filter((m: any) => m.pileCode === e.pileCode)
          }
        });
        console.log('pileObjArr', pileObjArr);
        if (pileObjArr && Object.keys(pileObjArr).length) {
          for (const l in pileObjArr) {
            const temGuns = pileObjArr[l].map((d, index) => {
              if (d.pileCode === '411230044') {
                console.log('DSDDDD', d);
              }
              return {
                ...d,
                gunName: index + 1,
                gunCode: d.pileCode + d.gunCode,
                carNum: '',
                lastSoc: d.soc,
                status: getStatus(d.gunStatus),
                code: d.gunCode,
                pileCode: d.pileCode,
                pileId: d.pileId,
              }
            }).sort((a, b) => {
              return a.gunCode - b.gunCode
            });
            temArr.push({
              pileCode: l,
              agreementId: temGuns && temGuns.length ? temGuns[0].agreementId : '',
              guns: [...temGuns]
            })
          }
        }
        yield put({
          type: 'setState',
          payload: {
            pileList: [...temArr],
            total,
            ...payload
          }
        })
      }
    }
  },
  reducers: {
    setState(state, {payload}){
      return {
        ...state,
        ...payload
      }
    }
  }
};
export default monitorModel;
